package com.xbkj.pgrp.server.dataproxy;

import com.xbkj.pgrp.server.model.app.Absence;
import com.xbkj.pgrp.server.model.app.Employee;
import com.xbkj.pgrp.server.model.app.MileStone;
import com.xbkj.pgrp.server.model.app.Project;
import com.xbkj.pgrp.server.model.common.WorkdayCalculator;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.jpa.dao.EruptDao;
import xyz.erupt.upms.model.EruptUserVo;
import xyz.erupt.upms.service.EruptUserService;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

@Service
public class EmployeeDataProxy implements DataProxy<Employee> {
    @Resource
    private EruptDao eruptDao;


    @Resource
    private EruptUserService eruptUserService;

    @Resource
    private WorkdayCalculator workdayCalculator;



    public void beforeAdd(Employee employee) {
        employee.setCreateTime(new Date());
        employee.setCreateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
        employee.setUpdateTime(new Date());
        employee.setUpdateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
    }

    public void beforeUpdate(Employee employee) {
        employee.setUpdateTime(new Date());
        employee.setUpdateUser(new EruptUserVo(this.eruptUserService.getCurrentUid()));
        saveAbsences(employee);
    }

    @Override
    public void afterAdd(Employee employee) {
        saveAbsences(employee);
    }

    private void saveAbsences(Employee employee) {
        if (employee.getAbsences() != null && employee.getAbsences().size() > 0) {
            for (Absence absence : employee.getAbsences()) {
                absence.setEmployee(employee);
                absence.setId(null);
                LocalDate beginDate = absence.getBeginDate().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
                LocalDate endDate = absence.getEndDate().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
                // 如果前台传入的天数小于计算出的天数，则使用前台传入的天数
                Long absenceDays = workdayCalculator.calculateWorkdays(beginDate, endDate);
                if(absence.getDays() > 0 && absence.getDays() <= absenceDays) {
                    absenceDays = absence.getDays();
                }
                // 设置请假天数
                absence.setDays(absenceDays);
                eruptDao.persist(absence);
            }
            eruptDao.flush();
        }
    }


}
